package main

import "fmt"

// 在一些情况下，程序没有足够的内存容量支持存储大量对象，
// 或者大量的对象存储着重复的状态，此时就会造成内存资源的浪费。

// 享元模式提出了这样的解决方案：如果多个对象中相同的状态可以共用，
// 就能在在有限的内存容量中载入更多对象。
type ColorFlyweightFactory struct {
	maps map[string]*ColorFlyweight
}

var colorFactory *ColorFlyweightFactory

func GetColorFlyweightFactory() *ColorFlyweightFactory {
	if colorFactory == nil {
		colorFactory = &ColorFlyweightFactory{
			maps: make(map[string]*ColorFlyweight),
		}
	}
	return colorFactory
}
func (f *ColorFlyweightFactory) Get(filename string) *ColorFlyweight {
	color := f.maps[filename]
	if color == nil {
		color = NewColorFlyweight(filename)
		f.maps[filename] = color
	}
	return color
}

type ColorFlyweight struct {
	data string
}

func NewColorFlyweight(filename string) *ColorFlyweight {
	data := fmt.Sprintf("color data %s", filename)
	return &ColorFlyweight{data: data}
}

type ColorViewer struct {
	*ColorFlyweight
}

func NewColorViewer(name string) *ColorViewer {
	color := GetColorFlyweightFactory().Get(name)
	return &ColorViewer{
		ColorFlyweight: color,
	}
}

func ExampleFlyweight() {
	viewer1 := NewColorViewer("blue")
	viewer2 := NewColorViewer("blue")

	fmt.Println(viewer1.ColorFlyweight == viewer2.ColorFlyweight)
}
